﻿using System.Reflection;
using System.Web.Security;
using Autofac;
using Autofac.Integration.Web.Mvc;
using FluentValidation;
using GiveAQuiz.Data;
using GiveAQuiz.Web.Authentication;
using GiveAQuiz.Web.Helpers;
using GiveAQuiz.Web.Membership;
using GiveAQuiz.Web.Messenger;
using GiveAQuiz.Web.Validation;

namespace GiveAQuizSite.Services
{
  /// <summary>
  /// This class serves as a central location to perform
  /// application initialization.
  /// </summary>
  public class Bootstraper
  {
    /// <summary>
    /// Initialize the AutoFac IoC container.
    /// </summary>
    /// <returns>The newly created AutoFac IoC container.</returns>
    public static IContainer InitializeContainer()
    {
      var builder = new ContainerBuilder();

      // register the MVC controllers
      builder.RegisterControllers(Assembly.GetExecutingAssembly());
      
      // register instance of the MembershipProvider
      builder.RegisterInstance<MembershipProvider>(Membership.Provider);

      // register helpers
      builder.RegisterType<WebPathHelper>().As<IWebPathHelper>().SingleInstance();

      // register services
      builder.RegisterType<FormsAuthenticationService>().As<IFormsAuthentication>().SingleInstance();
      builder.RegisterType<AccountMembershipService>().As<IMembershipService>().SingleInstance();
      builder.RegisterType<AccountMessenger>().As<IAccountMessenger>().SingleInstance();
      builder.RegisterType<SmtpMessageSender>().As<IMessageSender>().SingleInstance();

      // register repositories
      builder.RegisterType<QuizRepository>().As<IQuizRepository>().InstancePerLifetimeScope();

      // register validators from the GiveAQuiz.Web Assembly
      AssemblyScanner.FindValidatorsInAssembly(Assembly.GetAssembly(typeof(AutofacValidatorFactory)))
          .ForEach(result => builder.RegisterType(result.ValidatorType).As(result.InterfaceType).SingleInstance());

      // build the container
      return builder.Build();
    }
  }
}